//
//  PropertyExpensesListView.swift
//  SmartHousekeeper
//
//  Created by 张磊 on 2020/2/21.
//  Copyright © 2020 LS. All rights reserved.
//

import UIKit

class PropertyExpensesListView: UIView , UITableViewDelegate, UITableViewDataSource  {
    
    typealias PropertyExpensesListViewSwitchBlock = (_ isOn:Bool)->()
    public var switchBlock : PropertyExpensesListViewSwitchBlock? = nil
    
    typealias PropertyExpensesListViewPayBlock = ()->()
    public var payBlock : PropertyExpensesListViewPayBlock? = nil
    
    
    lazy var footer : UIView = {
        let value = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 80))
        return value
    }()
    
    
    lazy var allSelectBtn : UIButton = {
        let value = UIButton(textColor: RGBColor(r: 40, g: 40, b: 40, a: 1), textFont: UIFont.boldSystemFont(ofSize: Adapter(15)))
        value.setImage(UIImage(named: "icon_no_select"), for: .normal)
        value.setImage(UIImage(named: "icon_success"), for: .selected)
        value.setTitle("全选未付账单", for: .normal)
        value.backgroundColor = .white
        value.layer.cornerRadius = Adapter(8)
        value.layer.masksToBounds = true
        return value
    }()
    
    lazy var payView : UIView = {
        let value = UIView()
        value.backgroundColor = RGBColor(r: 62, g: 134, b: 230, a: 1)
        return value
    }()
    
    lazy var payL : UILabel = {
        let value = UILabel(textColor: .white, textFont: UIFont.boldSystemFont(ofSize: 16))
        value.text = "立即支付"
        return value
    }()
    lazy var moenyL : UILabel = {
        let value = UILabel(textColor: .white, textFont: UIFont.boldSystemFont(ofSize: 14))
        value.text = "0.00"
        return value
    }()
    
    lazy var tablewView : UITableView = {
        let value = UITableView(frame: CGRect.zero, style:.grouped)
        value.delegate = self
        value.dataSource = self
        value.separatorStyle = .none
        value.backgroundColor = .clear
        value.bounces = false
        return value
    }()
    var array =
        [["isPay":"0", "month":"04月", "year":"2020年","price":"150.00","no":"34234234","isSelect":"0"],
         ["isPay":"0", "month":"03月", "year":"2020年","price":"150.00","no":"34234234","isSelect":"0"],
         ["isPay":"0", "month":"02月", "year":"2020年","price":"150.00","no":"34234234","isSelect":"0"],
         ["isPay":"1", "month":"01月", "year":"2020年","price":"150.00","no":"34234234","isSelect":"0"]]
    
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }
    func setUI() {
        self.addSubview(tablewView)
        tablewView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.bottom.equalToSuperview().offset(-Adapter(80))
        }
        self.addSubview(footer)
        footer.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(tablewView.snp.bottom)
        }
        
        
        
        footer.addSubview(allSelectBtn)
        allSelectBtn.snp.makeConstraints { (make) in
            make.left.top.bottom.equalToSuperview()
            make.width.equalTo((ScreenWidth / 5.0 * 3.0))
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            self.allSelectBtn.imagePosition(at: .left, space: 10)
        }
        
        //全选方法
        allSelectBtn.sce.add(.touchUpInside) { (btn) in
            btn.isSelected = !btn.isSelected
            self.allSelectCell(btn.isSelected)
            self.moenyL.text = self.calculateSelectPrice()

        }
        
                
        footer.addSubview(payView)
        payView.snp.makeConstraints { (make) in
            make.right.top.bottom.equalToSuperview()
            make.width.equalTo((ScreenWidth / 5.0 * 2.0))
        }
        
        payView.addSubview(payL)
        payL.snp.makeConstraints { (make) in
            make.bottom.equalTo(payView.snp.centerY).offset(Adapter(-5))
            make.centerX.equalToSuperview()
        }
        
        payView.addSubview(moenyL)
        moenyL.snp.makeConstraints { (make) in
            make.top.equalTo(payView.snp.centerY).offset(Adapter(5))
            make.centerX.equalToSuperview()
        }
        
        let touch = UITapGestureRecognizer(target: self, action: #selector(payAction))
        payView.addGestureRecognizer(touch)
        
    }
    private func allSelectCell(_ isSelect:Bool) {
        var arr = Array<Any>()
        for dic in array {
            var dicMU = dic
            if isSelect == true {
                dicMU.updateValue("1", forKey: "isSelect")
            } else {
                dicMU.updateValue("0", forKey: "isSelect")
            }
            arr.append(dicMU)
        }
        array = arr as! [[String : String]]
        tablewView.reloadData()
    }
    //判断是否为全选
    private func isAllSelectCell() -> Bool {
        for dic in array {
            if dic["isSelect"] == "0" && dic["isPay"] == "0"{
                return false
            }
        }
        return true
        
    }
    //立即支付
    @objc func payAction() {
        self.payBlock?()
    }
    //计算金额
    private func calculateSelectPrice() -> (String){
        var price = Float()
        for dic in array {
            if dic["isSelect"] == "1" && dic["isPay"] == "0"{
                let nsstring = dic["price"]! as NSString
                let f = nsstring.floatValue
                price = price + f
            }
        }
        return "\(price)"
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return Adapter(80)
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var dic = array[indexPath.row]
        guard dic["isPay"] == "0" else {
            return
        }
        if dic["isSelect"] == "0" {
            dic.updateValue("1", forKey: "isSelect")
        } else {
            dic.updateValue("0", forKey: "isSelect")
        }
        array[indexPath.row] = dic
        tableView.reloadData()
        allSelectBtn.isSelected = isAllSelectCell()
        moenyL.text = calculateSelectPrice()
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "PropertyExpensesListTableViewCell") as? PropertyExpensesListTableViewCell
        if cell == nil{
            cell = PropertyExpensesListTableViewCell.init(style: .default, reuseIdentifier: "PropertyExpensesListTableViewCell")
        }
        let dic = array[indexPath.row]
        
        if dic["isPay"] == "1" {
            cell?.imgSelect.image = UIImage(named: "icon_payed")
        } else {
            if dic["isSelect"] == "1" {
                cell?.imgSelect.image = UIImage(named: "icon_success")
            } else {
                cell?.imgSelect.image = UIImage(named: "icon_no_select")
                
            }
        }
        if array.count == 1 {
            cell?.lineTop.isHidden = true
            cell?.lineBottom.isHidden = true
        } else {
            if indexPath.row == 0 {
                cell?.lineTop.isHidden = true
                cell?.lineBottom.isHidden = false
            } else if indexPath.row == array.count - 1{
                cell?.lineTop.isHidden = false
                cell?.lineBottom.isHidden = true
            } else {
                cell?.lineTop.isHidden = false
                cell?.lineBottom.isHidden = false
            }
        }
        cell?.selectionStyle = .none
        cell?.backgroundColor = .clear
        return cell!
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return Adapter(110)
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = PropertyExpensesListTableViewHeaderView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: Adapter(110)))
        
        header.switchV.sce.add(.valueChanged) { (switchV) in
            self.switchBlock?(switchV.isOn)
        }
        
        return header
    }
}
